import { getVerificationCode, login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import to from '@/to'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  depts: [],
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_DEPTS: (state, depts) => {
    state.depts = depts
  }
}

const actions = {
  // 获取验证码
  async getVerificationCode() {
    const [err, response] = await to(getVerificationCode())
    if (err) {
      throw new Error(err.message)
    }
    return response.data
  },
  // 用户登录
  async login({ commit }, userInfo) {
    const { username, password, captcha } = userInfo
    const [err, response] = await to(login(username, password, captcha))
    if (err) {
      throw new Error(err.message)
    }
    const responseData = response.data
    if (responseData.resultCode !== '200') {
      throw new Error(`${responseData.errorDesc}`)
    }
    const token = responseData.data
    commit('SET_TOKEN', token)
    return true
  },
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    const [err, response] = await to(getUserInfo())
    if (err) {
      throw new Error(err.message)
    }
    const responseData = response.data
    if (responseData.resultCode !== '200') {
      throw new Error(`${responseData.errorDesc}`)
    }
    const data = responseData.data
    // 验证角色为非空数组
    if (data.roles && data.roles.length > 0) {
      commit('SET_ROLES', data.roles)
    }
    commit('SET_NAME', data.username)
    commit('SET_AVATAR', '')
    commit('SET_INTRODUCTION', data.realname)
    commit('SET_DEPTS', data.depts)
    return responseData
  },

  // 用户退出
  async logout({ commit, state }) {
    // eslint-disable-next-line no-unused-vars
    const [err, response] = await to(logout({ username: state.name }))
    if (err) {
      throw new Error(err.message)
    }
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    resetRouter()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
